package com.fone.player.online.adapter;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.fone.player.ApplicationManage;
import com.fone.player.R;
import com.fone.player.cache.ImageDownloadModule;
import com.fone.player.client.Request;
import com.fone.player.client.SpecllistRst;
import com.fone.player.client.SpecllistRst.Col;
import com.fone.player.client.SpecllistRst.Poster;
import com.fone.player.entity.HorizontalInfo;
import com.fone.player.entity.RedirectInfo;
import com.fone.player.online.activity.SubjectActivity;
import com.fone.player.play.PlayerFrom;
import com.fone.player.util.Activity2poster;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.FoneWebViewClient;
import com.fone.player.util.ScreenUtil;
import com.fone.player.util.WebViewAction;
import com.fone.player.view.PostersView;
import com.fone.player.view.ReGridView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

/**
 * GridView 模式的adapter，包含横版和竖版
 */
@DelegateAdaptersAnnotation(delegateAdapters = { GridModeAdapter.PosterViewAdapter.class, GridModeAdapter.WebViewAdapter.class, GridModeAdapter.GridViewAdapter.class })
public class GridModeAdapter extends DispatcherAdapter {

	/** 日志标签 */
	// private static final String TAG = "HorizontalAdapter";

	private List<HorizontalInfo> horizontalList;
	private SpecllistRst specllistRst;
	private Poster poster;
	private Col webcol;
	private String shost;
	private static String host;
	private int plusPosition = 0;
	public int showtype;
	private HorizontalAdapterItem adapterItem;

	public GridModeAdapter(Context context, SpecllistRst rst, List<HorizontalInfo> hlist, int type) {
		super(context);
		mContext = context;
		this.specllistRst = rst;
		horizontalList = hlist;
		showtype = type;
		initData();
	}

	private void initData() {
		if (specllistRst != null) {
			shost = specllistRst.shost;
			host = specllistRst.host;
			plusPosition = 0;
			// 是否有webview
			if (specllistRst.cols != null && specllistRst.cols.colList != null) {
				for (Col col : specllistRst.cols.colList) {
					if (col.type == 2) {
						webcol = col;
						plusPosition++;
						break;
					}
				}
			} else {
				webcol = null;
			}
			// 是否有海报
			if (!TextUtils.isEmpty(specllistRst.showposter) && specllistRst.showposter.trim().equals("1")
					&& specllistRst.poster != null && specllistRst.poster.cnts != null) {
				// 有海报，是否有webview
				poster = specllistRst.poster;
				plusPosition++;
			} else {
				// 没有海报
				poster = null;
			}
		} else {
			// 没有海报
			poster = null;
			// 没有webview
			webcol = null;
			plusPosition = 0;
		}

	}

	public void setData(SpecllistRst t, List<HorizontalInfo> hlist) {
		horizontalList = hlist;
		specllistRst = t;
		initData();
		notifyDataSetChanged();
	}

	@Override
	public int getCount() {
		int count = 0;
		if (poster != null) {
			count++;
		}
		if (webcol != null) {
			count++;
		}
		int numColume;
		if (showtype == 11) {
			numColume = 2;
		} else {
			numColume = 3;
		}
		if (horizontalList != null) {
			if (horizontalList.size() > 0) {
				count = count + ((horizontalList.size() - 1) / numColume + 1);
			}
		}
		return count;
	}

	@Override
	public Object getItem(int position) {
		if (adapterItem != null) {
			adapterItem = null;
		}
		adapterItem = new HorizontalAdapterItem(poster, webcol, shost, plusPosition, showtype, horizontalList);
		return adapterItem;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public int getItemViewType(int position) {
		switch (position) {
		case 0:
			// 是否有海报
			if (poster != null) {
				// 有海报
				return 0;
			} else {
				// 是否有webview
				if (webcol != null) {
					return 1;
				} else {
					return 2;
				}
			}
		case 1:
			// 是否有海报
			if (poster != null) {
				// 有海报
				// 是否有webview
				if (webcol != null) {
					return 1;
				} else {
					return 2;
				}
			} else {
				return 2;
			}
		default:
			return 2;
		}
	}

	/**
	 * 海报模版
	 * 
	 * @author kongxiaojun
	 * @since 2014-7-9
	 */
	@DelegateAdapterType(itemType = 0)
	public static class PosterViewAdapter extends HorizontalDelegateAdapter {
		private PostersView posterView;

		@Override
		public View getView(int position, View convertView, ViewGroup parent, LayoutInflater inflater, Object item) {
			HorizontalAdapterItem adapterItem = (HorizontalAdapterItem) item;
			if (posterView == null) {
				posterView = new PostersView(inflater.getContext());
				posterView.setLayoutParams(new AbsListView.LayoutParams(LayoutParams.MATCH_PARENT, ScreenUtil.dp2px(126)));
			}
			posterView.initData(false, adapterItem.shost, host, adapterItem.poster.cnts.cntList, PlayerFrom.BANNER_COLLECTION);
			return posterView;
		}
	}

	/**
	 * WebView模版
	 * 
	 * @author kongxiaojun
	 * @since 2014-7-9
	 */
	@DelegateAdapterType(itemType = 1)
	public static class WebViewAdapter extends HorizontalDelegateAdapter {

		private WebView mWebView;

		@Override
		public View getView(int position, View convertView, ViewGroup parent, LayoutInflater inflater, Object item) {
			HorizontalAdapterItem adapterItem = (HorizontalAdapterItem) item;
			if (mWebView == null) {
				mWebView = new WebView(ApplicationManage.getGlobalContext());
//				mWebView.enablePlatformNotifications();
				mWebView.setLayoutParams(new AbsListView.LayoutParams(LayoutParams.MATCH_PARENT, 1));
				mWebView.setBackgroundColor(0);
				// 设置WebView属性，能够执行Javascript脚本
				mWebView.getSettings().setJavaScriptEnabled(true);
				mWebView.setWebViewClient(new FoneWebViewClient());
				mWebView.addJavascriptInterface(new WebViewAction(inflater.getContext()), "Fone");
			}
			mWebView.setLayoutParams(new AbsListView.LayoutParams(LayoutParams.MATCH_PARENT, ScreenUtil.dp2px(adapterItem.webCol.h)));
			mWebView.loadUrl(adapterItem.webCol.url);
			return mWebView;
		}
	}

	/**
	 * GirdView模版
	 * 
	 * @author kongxiaojun
	 * @since 2014-7-9
	 */
	@DelegateAdapterType(itemType = 2)
	public static class GridViewAdapter extends HorizontalDelegateAdapter {

		private DisplayImageOptions mOptions = new DisplayImageOptions.Builder().cacheInMemory(true)// 设置下载的图片是否缓存在内存中
				.cacheOnDisk(true)// 设置下载的图片是否缓存在SD卡中
				.build();

		@Override
		public View getView(int position, View convertView, ViewGroup parent, final LayoutInflater inflater, Object item) {
			HorizontalAdapterItem adapterItem = (HorizontalAdapterItem) item;
			ViewHolder holder = null;
			if (convertView == null || convertView.getTag() == null) {
				if (adapterItem.showtype == 11) {
					// 横版
					convertView = inflater.inflate(R.layout.view_grid_horizontal, parent, false);
					holder = new ViewHolder((ReGridView) convertView.findViewById(R.horizontal.grid));
				} else {
					// 竖版
					convertView = inflater.inflate(R.layout.view_grid_vertical, parent, false);
					holder = new ViewHolder((ReGridView) convertView.findViewById(R.vertical.grid));
				}
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			// 可将行间隔及列间隔常量化
			int listPosition = position - adapterItem.plusPosition;
			GridCntAdapter adapter = new GridCntAdapter(mOptions, listPosition, adapterItem.showtype, adapterItem.shost, adapterItem.infos,inflater);
			holder.reGridView.setAdapter(adapter);
			holder.reGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
					// 判断网络状态
					if (FoneUtil.isNetOkWithToast(inflater.getContext())) {
						HorizontalInfo info = (HorizontalInfo) arg0.getAdapter().getItem(arg2);
						Activity2poster.startActivity(inflater.getContext(), getRedirectInfo(info));
					}
				}
			});
			return convertView;
		}

		private RedirectInfo getRedirectInfo(HorizontalInfo info) {
			RedirectInfo redirectInfo = new RedirectInfo();
			redirectInfo.host = host;
			redirectInfo.utp = info.utp;
			redirectInfo.weibourl = info.weibourl;
			redirectInfo.url = info.url;
			redirectInfo.vgurl = info.url;
			redirectInfo.xyzplayurl = info.url;
			redirectInfo.dnfs = info.dfnt;
			redirectInfo.name = info.name;
			redirectInfo.ourl = info.ourl;
			redirectInfo.btnply = info.btnply;
			redirectInfo.pic = info.pic2;
			return redirectInfo;
		}

		public static class ViewHolder {
			public ReGridView reGridView;

			public ViewHolder(ReGridView reGridView) {
				super();
				this.reGridView = reGridView;
			}
		}

		public static class GridCntAdapter extends BaseAdapter {

			private DisplayImageOptions mOptions;
			/** 此处listPosition 是去掉header和海报以及webview的postion */
			private int listPosition;
			/** 每行显示多少项 */
			int numColumns;
			private String shost;
			private List<HorizontalInfo> horizontalList;
			private LayoutInflater inflater;

			public GridCntAdapter(DisplayImageOptions mOptions, int listPosition, int showtype, String shost, List<HorizontalInfo> horizontalList,LayoutInflater inflater) {
				super();
				this.mOptions = mOptions;
				this.listPosition = listPosition;
				this.horizontalList = horizontalList;
				this.inflater = inflater;
				if (showtype == 11) {
					numColumns = 2;
				} else {
					numColumns = 3;
				}
				this.shost = shost;
			}

			@Override
			public int getCount() {
				return (horizontalList.size() - listPosition * numColumns) >= numColumns ? numColumns : horizontalList.size() - listPosition * numColumns;
			}

			@Override
			public Object getItem(int position) {
				return horizontalList.get(horizontalList.size() - ((horizontalList.size() - listPosition * numColumns) - position));
			}

			@Override
			public long getItemId(int position) {
				return 0;
			}

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				HorizontalInfo info = (HorizontalInfo) getItem(position);

				ViewHolder vHolder = null;
				if (convertView == null) {
					if (numColumns == 2) {// 横版
						convertView = inflater.inflate(R.layout.item_horizontal, null);
						// 创建 ViewHodler 对象
						vHolder = new ViewHolder((ImageView) convertView.findViewById(R.horizontal.pic), (TextView) convertView.findViewById(R.horizontal.name), (TextView) convertView.findViewById(R.horizontal.progress), (TextView) convertView.findViewById(R.horizontal.score));
					} else {
						// 竖版
						convertView = inflater.inflate(R.layout.item_vertical, null);
						// 创建 ViewHodler 对象
						vHolder = new ViewHolder((ImageView) convertView.findViewById(R.vertical.pic), (TextView) convertView.findViewById(R.vertical.name), (TextView) convertView.findViewById(R.vertical.type), (TextView) convertView.findViewById(R.vertical.score));
					}
					// 设置 Tag
					convertView.setTag(vHolder);
				} else {
					vHolder = (ViewHolder) convertView.getTag();
				}

				if (numColumns == 2) {
					ImageDownloadModule.getInstance().download(FoneUtil.getAbsoluteUrl("", shost, info.pic2), vHolder.pic, mOptions);
				} else {
					ImageDownloadModule.getInstance().download(FoneUtil.getAbsoluteUrl("", shost, info.pic1), vHolder.pic, mOptions);
				}

				vHolder.title.setText(info.name);
				vHolder.score.setText(setQuality(info.quality));
				if (numColumns == 2) {
					setUpdatedetail(info.updatedetail, vHolder.progress);
				} else {
					setType(info.ftv, vHolder.progress);
				}
				return convertView;
			}

			public static class ViewHolder {
				ImageView pic;
				TextView title;
				TextView progress;
				TextView score;

				public ViewHolder(ImageView pic, TextView title, TextView progress, TextView score) {
					super();
					this.pic = pic;
					this.title = title;
					this.progress = progress;
					this.score = score;
				}
			}

			private void setUpdatedetail(String updatedetail, TextView textView) {
				if (!TextUtils.isEmpty(updatedetail)) {
					textView.setVisibility(View.VISIBLE);
					textView.setText(updatedetail);
				}
			}

			/**
			 * 显示当前VIP
			 */
			private void setType(String ftv, TextView textView) {

				if (!TextUtils.isEmpty(ftv) && ftv.equals("1")) {
					textView.setVisibility(View.VISIBLE);
					textView.setText("VIP");
				}
			}

			private String setQuality(String quality) {
				if (TextUtils.isEmpty(quality)) {
					return "暂无分数";
				} else {
					return FoneUtil.String2Integer(quality) * 2 + "分";
				}
			}
		}
	}

	// /**
	// * 显示当前VIP
	// */
	// private void setType(String ftv, TextView textView) {
	//
	// if (!TextUtils.isEmpty(ftv) && ftv.equals("1")) {
	// textView.setVisibility(View.VISIBLE);
	// textView.setText("VIP");
	// }
	// }

	public static class HorizontalDelegateAdapter implements DelegateAdapter {

		DisplayImageOptions options = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.default_image_bg).showImageForEmptyUri(R.drawable.default_image_bg).showImageOnFail(R.drawable.default_image_bg).cacheInMemory(true).cacheOnDisk(true).considerExifParams(true).build();

		@Override
		public View getView(int position, View convertView, ViewGroup parent, LayoutInflater inflater, Object item) {
			// TODO Auto-generated method stub
			return convertView;
		}

		/**
		 * 设置图片
		 */
		protected void setImageView(ImageView imageView, int defaultResourceId, String url) {
			// 设置图片
			ImageLoader.getInstance().displayImage(FoneUtil.getAbsoluteUrl("", Request.getInstance().getSHost(), url), imageView, options);
		}

		/**
		 * 推荐维度 0 无纬度 1 时长 2 评分 3 更新至 4 自定义文字 5 自定义图片
		 */
		protected void getRmd(String rmd, String rmdval, TextView textView, ImageView imageView) {
			if (rmd.equals("1")) {
				textView.setVisibility(View.VISIBLE);
				imageView.setVisibility(View.INVISIBLE);
				textView.setText("播放时长" + rmdval.substring(0, 5));
			} else if (rmd.equals("2")) {
				textView.setVisibility(View.VISIBLE);
				imageView.setVisibility(View.INVISIBLE);
				textView.setText(rmdval + "分");
			} else if (rmd.equals("3")) {
				textView.setVisibility(View.VISIBLE);
				imageView.setVisibility(View.INVISIBLE);
				textView.setText(rmdval);
			} else if (rmd.equals("4")) {
				textView.setVisibility(View.VISIBLE);
				imageView.setVisibility(View.INVISIBLE);
				textView.setText(rmdval);
			} else if (rmd.equals("5")) {
				textView.setVisibility(View.INVISIBLE);
				imageView.setVisibility(View.VISIBLE);
				setImageView(imageView, R.drawable.default_image_bg, rmdval);
				imageView.setVisibility(View.VISIBLE);
			} else {

			}
		}

		/**
		 * 显示当前影片类型
		 * 
		 * 当影片为收费视频时，显示VIP 否则显示对应类型
		 * 
		 * ftv 当前视频是否收费 0 否 1 是 favtyp 收藏类型，内容类型(0 全部 1 电影 2 电视剧 3 动漫 4 综艺 5 原创
		 * 6 视频直播 7 音频直播 8 新闻 9 短片)
		 */
		protected void setType(String ftv, String favtyp, TextView textview) {

			if (TextUtils.isEmpty(ftv) || TextUtils.isEmpty(favtyp)) {
			} else if (ftv.equals("1")) {
				textview.setVisibility(View.VISIBLE);
				textview.setText("VIP");
			}
		}

		/**
		 * 控件相应监听
		 */

		protected class MoreClicker implements OnClickListener {
			Context mContext;
			String url;

			public MoreClicker(String url, Context context) {
				super();
				this.url = url;
				mContext = context;
			}

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// 判断网络状态
				if (FoneUtil.isNetOk(mContext)) {
					Intent intent = new Intent(mContext, SubjectActivity.class);
					intent.putExtra("url", url);
					mContext.startActivity(intent);
				}
			}
		}

	}

	public static class HorizontalAdapterItem {
		public Poster poster;
		public Col webCol;
		public String shost;
		public int plusPosition;
		public int showtype;
		public List<HorizontalInfo> infos;

		public HorizontalAdapterItem(Poster poster, Col webCol, String shost, int plusPosition, int showtype, List<HorizontalInfo> infos) {
			super();
			this.poster = poster;
			this.webCol = webCol;
			this.shost = shost;
			this.plusPosition = plusPosition;
			this.showtype = showtype;
			this.infos = infos;
		}
	}
}
